package com.elbis.business.manager;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.elbis.business.entity.Game;
import com.elbis.util.HibernateUtil;

public class GameManager implements EntityManager<Game> {

	private static final Logger logger = Logger.getLogger(GameManager.class);

	@Override
	public void delete(Game game) {
		Session session = HibernateUtil.getSession();
		Transaction trx = null;
		try {
			trx = session.beginTransaction();
			session.delete(game);
			trx.commit();
		} catch (HibernateException e) {
			if (trx != null) {
				trx.rollback();
			}
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
	}

	@Override
	public void update(Game game) {
		Session session = HibernateUtil.getSession();
		Transaction trx = null;
		try {
			trx = session.beginTransaction();
			session.update(game);
			trx.commit();
		} catch (HibernateException e) {
			if (trx != null) {
				trx.rollback();
			}
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
	}

	public Game getGame(String gameName) {
		Game game = null;
		Session session = HibernateUtil.getSession();
		try {
			game = (Game) session.createCriteria(Game.class)
					.add(Restrictions.and(Restrictions.eq("name", gameName)))
					.uniqueResult();

		} catch (HibernateException e) {
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
		return game;
	}

	@Override
	public Long save(Game game) {
		Session session = HibernateUtil.getSession();
		Transaction trx = null;
		Long id = null;
		try {
			trx = session.beginTransaction();
			id = (Long) session.save(game);
			trx.commit();
		} catch (HibernateException e) {
			if (trx != null) {
				trx.rollback();
			}
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
		return id;
	}

}
